package com.example.websocketserver.configuration.handler;

import com.example.websocketserver.pojo.HomeHubWebsocketPrincipal;
import com.example.websocketserver.pojo.WebSocketConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

import java.security.Principal;
import java.util.Map;

/**
 * @author liulei
 * @version 1.0
 */
@Slf4j
@Component
public class WebsocketShakeHandler extends DefaultHandshakeHandler {

    @Override
    protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map<String, Object> attributes) {
        // 将客户端标识封装为Principal对象，从而让服务端能通过getName()方法找到指定客户端
        Object userId = attributes.get(WebSocketConstants.USER_ID_KEY);
        if (userId == null) {
            logger.error("websocket->determineUser user info null");
            return null;
        }
        log.info("websocket->determineUser user info {}", userId);
        return new HomeHubWebsocketPrincipal(String.valueOf(userId));
    }

}
